package com.zbkj.front.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.user.User;
import com.zbkj.common.model.user.UserTag;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.PasswordRequest;
import com.zbkj.common.request.UserBindingPhoneUpdateRequest;
import com.zbkj.common.request.UserEditInfoRequest;
import com.zbkj.common.response.CommonUserListResponse;
import com.zbkj.common.response.CommunityRecommendAuthorResponse;
import com.zbkj.common.response.UserInfoResponse;
import com.zbkj.common.response.UserLogoffBeforeResponse;
import com.zbkj.common.result.CommonResult;
import com.zbkj.common.result.Result;
import com.zbkj.common.result.ResultUtils;
import com.zbkj.common.session.SessionContext;
import com.zbkj.common.session.UserSession;
import com.zbkj.common.util.BeanUtils;
import com.zbkj.common.vo.OnlineTerminalVO;
import com.zbkj.common.vo.UserVO;
import com.zbkj.service.service.UserService;
import com.zbkj.service.service.UserTagService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.List;

/**
 * 用户 -- 用户中心
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
@Slf4j
@RestController
@RequestMapping("api/front/user")
@Api(tags = "用户控制器")
public class UserController {
    @Autowired
    UserTagService userTagService;

    @GetMapping("/terminal/online")
    @ApiOperation(value = "判断用户哪个终端在线", notes = "返回在线的用户id的终端集合")
    public Result<List<OnlineTerminalVO>> getOnlineTerminal(@NotEmpty @RequestParam("userIds") String userIds) {
        return ResultUtils.success(userService.getOnlineTerminals(userIds));
    }


    @GetMapping("/self")
    @ApiOperation(value = "获取当前用户信息", notes = "获取当前用户信息")
    public Result<UserVO> findSelfInfo() {
        User user = userService.getInfo();
//        UserSession session = SessionContext.getSession();
//        User user = userService.getById(session.getUserId());
        UserVO userVO = new UserVO();
        userVO.setNickName(user.getNickname());
        userVO.setHeadImage(user.getAvatar());
        userVO.setHeadImageThumb(user.getAvatar());
        userVO.setId(user.getId());
        return ResultUtils.success(userVO);

    }


    @GetMapping("/find/{id}")
    @ApiOperation(value = "查找用户", notes = "根据id查找用户")
    public Result<UserVO> findById(@NotEmpty @PathVariable("id") Long id) {
        return ResultUtils.success(userService.findUserById(id));
    }



    @GetMapping("/findByName")
    @ApiOperation(value = "查找用户", notes = "根据用户名或昵称查找用户")
    public Result<List<UserVO>> findByName(@RequestParam("name") String name) {
        return ResultUtils.success(userService.findUserByName(name));
    }

    @GetMapping("/findByZone")
    @ApiOperation(value = "板块用户推荐", notes = "根据用户名或昵称查找用户")
    public CommonPage<CommonUserListResponse> findByZone(@RequestParam(value = "zone",required = false) Integer zone, PageParamRequest request) {
        return CommonPage.restPage(userService.findByZone(zone,request));
    }

    @GetMapping("/getByJob2")
    @ApiOperation(value = "板块用户推荐", notes = "根据用户名或昵称查找用户")
    public CommonPage<CommonUserListResponse> getByJob(@RequestParam(name = "id", required = false) Integer id,@RequestParam(name = "name", required = false)String name, PageParamRequest request) {
        return CommonPage.restPage(userService.findByJob(id,name,request));
    }
    @GetMapping("/tagNameById")
    @ApiOperation(value = "板块用户推荐", notes = "查tag名字")
    public CommonResult<String> tagNameById(@RequestParam("id") Integer id) {
        UserTag userTag = userTagService.getById(id);
        return CommonResult.success(userTag.getName());
    }



    @Autowired
    private UserService userService;

    @ApiOperation(value = "手机号修改密码")
    @RequestMapping(value = "/register/reset", method = RequestMethod.POST)
    public CommonResult<Boolean> password(@RequestBody @Validated PasswordRequest request) {
        return CommonResult.success(userService.password(request));
    }

    @ApiOperation(value = "修改个人信息")
    @RequestMapping(value = "/user/edit", method = RequestMethod.POST)
    public CommonResult<String> personInfo(@RequestBody @Validated UserEditInfoRequest request) {
        if (userService.editUser(request)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @ApiOperation(value = "修改个人信息")
    @RequestMapping(value = "/user/editTag", method = RequestMethod.POST)
    public CommonResult<String> editTag(@RequestBody @Validated String TagIds) {
       try {
           Integer userId = userService.getUserIdException();
           User user = userService.getById(userId);
           user.setTagId(TagIds);
           return CommonResult.success();
       }catch (Exception e){
           return CommonResult.failed(e.getMessage());
       }
    }

    @ApiOperation(value = "用户信息")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public CommonResult<UserInfoResponse> getUserCenter() {
        return CommonResult.success(userService.getUserInfo());
    }

    @ApiOperation(value = "获取用户手机号验证码")
    @RequestMapping(value = "/phone/code", method = RequestMethod.POST)
    public CommonResult<String> getCurrentPhoneCode() {
        if (userService.getCurrentPhoneCode()) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @ApiOperation(value = "换绑手机号获取验证码")
    @RequestMapping(value = "/update/binding/phone/code", method = RequestMethod.POST)
    public CommonResult<String> updatePhoneCode(@RequestBody @Validated UserBindingPhoneUpdateRequest request) {
        if (userService.updatePhoneCode(request)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @ApiOperation(value = "换绑手机号")
    @RequestMapping(value = "/update/binding", method = RequestMethod.POST)
    public CommonResult<String> updatePhone(@RequestBody @Validated UserBindingPhoneUpdateRequest request) {
        if (userService.updatePhone(request)) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @ApiOperation(value = "用户注销数据前置")
    @RequestMapping(value = "/logoff/before", method = RequestMethod.GET)
    public CommonResult<UserLogoffBeforeResponse> logoffBefore() {
        return CommonResult.success(userService.logoffBefore());
    }

    @ApiOperation(value = "用户注销")
    @RequestMapping(value = "/logoff", method = RequestMethod.POST)
    public CommonResult<String> logoff() {
        if (userService.logoff()) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }


//    @PreAuthorize("hasAuthority('platform:user:tag:list')")
    @ApiOperation(value = "用户标签分页列表") //配合swagger使用
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<UserTag>> getList(@Validated PageParamRequest pageParamRequest) {
        CommonPage<UserTag> userTagCommonPage = CommonPage.restPage(userTagService.getList(pageParamRequest));
        return CommonResult.success(userTagCommonPage);
    }

    @ApiOperation(value = "新增用户tag") //配合swagger使用
    @RequestMapping(value = "/addUserTag", method = RequestMethod.POST)
    public CommonResult<String> addUserTag(@RequestBody String tag) {
        try{
            LambdaQueryWrapper<UserTag> lqw = new LambdaQueryWrapper<>();
            lqw.eq(UserTag::getName,tag);
            UserTag userTag = userTagService.getOne(lqw);
            userTag.setName(tag);
            userTagService.saveOrUpdate(userTag);
            return CommonResult.success("success");
        }catch (Exception e){
            return CommonResult.failed(e.getMessage());
        }

    }


    @ApiOperation(value = "根据tag名字查用户") //配合swagger使用
    @RequestMapping(value = "/findByTagName", method = RequestMethod.POST)
    public CommonPage<User> findByTagName(@RequestBody String tag,@RequestBody PageParamRequest request) {
        Page<User> page = PageHelper.startPage(request.getPage(), request.getLimit());
            LambdaQueryWrapper<UserTag> lqw = new LambdaQueryWrapper<>();
            lqw.eq(UserTag::getName,tag);
            UserTag userTag = userTagService.getOne(lqw);
            if(userTag.getId()!=null) {
                LambdaQueryWrapper<User> lqw2 = new LambdaQueryWrapper<>();
                lqw2.apply("FIND_IN_SET(" + userTag.getId() + ", tag_id) > 0");
                List<User> list1 = userService.list(lqw2);
                return CommonPage.restPage(CommonPage.copyPageInfo(page, list1));
            }
            throw  new CrmebException("查询出错");
    }




}



